//
//  AsynchonousDownload.m
//  Alfresco
//
//  Created by Michael Muller on 10/16/09.
//  Copyright 2010 Zia Consulting.  Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
//

#import "AsynchonousDownload.h"
#import "Utility.h"

@implementation AsynchonousDownload

@synthesize data;
@synthesize url;
@synthesize delegate;
@synthesize urlConnection;

- (void) dealloc {
	[data release];
	[url release];
	[urlConnection release];
	[super dealloc];
}

- (AsynchonousDownload *) initWithURL:(NSURL *)u delegate:(id <AsynchronousDownloadDelegate>) del {
	
	NSLog(@"initializing asynchronous download from: %@", u);
	
	NSMutableData *d = [[NSMutableData alloc] init];
	self.data = d;
	[d release];
	
	self.url = u;
	self.delegate = del;
	
	return self;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	if ([response respondsToSelector:@selector(statusCode)])
	{
		int statusCode = [((NSHTTPURLResponse *)response) statusCode];
		if (statusCode >= 400)
		{
			[connection cancel];  // stop connecting; no more delegate messages
			NSString *msg = [[NSString alloc] initWithFormat: @"%d %@", statusCode, [NSHTTPURLResponse localizedStringForStatusCode:statusCode]];
			NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:msg forKey:NSLocalizedDescriptionKey];
			NSError *statusError = [NSError errorWithDomain:@"httpResponseErrorDomain" code:statusCode userInfo:errorInfo];
			[self connection:connection didFailWithError:statusError];
			[msg release];
		}
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)chunk {
    [self.data appendData:chunk];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	
	// stop the "network activity" spinner 
	stopSpinner();

	// if it's an auth failure
	if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == -1012) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Authentication Failure" message:@"Please check your username and password in the iPhone settings for Fresh Docs" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	}
	
	// let the user know something else bad happened
	else {
		NSString *msg = [[NSString alloc] initWithFormat:@"The server returned an error connecting to %@\n\n%@", [self.url absoluteURL], [error localizedDescription]];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection error" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[msg release];
	}
	
	if (self.delegate) {
		[delegate asyncDownload:self didFailWithError:error];
	}
}
 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

	// log the response
	NSString *responseAsString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	NSLog(@"async result: %@", responseAsString);
	[responseAsString release];
	
	// stop the "network activity" spinner 
	stopSpinner();

	if (self.delegate) {
		[delegate asyncDownloadDidComplete:self];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
	if ([challenge previousFailureCount] > 0) {
		[challenge.sender cancelAuthenticationChallenge:challenge];
	}
	else {
		NSString *user = userPrefUsername();
		NSString *pass = userPrefPassword();
		NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:user password:pass persistence:NSURLCredentialPersistenceNone];
		[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
		[credential release];
	}
}

- (void) start {
	// start downloading
	NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
	self.urlConnection = [NSURLConnection connectionWithRequest:requestObj delegate:self];
	[self.urlConnection start];
	
	// start the "network activity" spinner 
	startSpinner();
}

@end
